angular.module('inspinia',['angularFileUpload','uiSwitch']).controller('appMenuQueryCtrl',function($scope,$http,i18nService,SweetAlert,$document,FileUploader){
    i18nService.setCurrentLang('zh-cn');  //设置语言为中文
    $scope.paginationOptions=angular.copy($scope.paginationOptions);
    $scope.addInfo={};
    //是否带参数
    $scope.isWithParamList=[{text:"是",value:'1'},{text:"否",value:'0'}];

    //清空
    $scope.clear=function(){
        $scope.info={};
    };
    $scope.clear();

    $scope.userGrid={                           //配置表格
        data: 'result',
        paginationPageSize:10,                  //分页数量
        paginationPageSizes: [10,20,50,100],	//切换每页记录数
        useExternalPagination: true,		    //开启拓展名
        enableHorizontalScrollbar: true,        //横向滚动条
        enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs:[                           //表格数据
            { field: 'appName',displayName:'APP名称',width:180},
            { field: 'btnName',displayName:'菜单名称',width:180 },
            { field: 'startTime',displayName:'开启时间-开始时间',cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"',width:180},
            { field: 'endTime',displayName:'开启时间-结束时间',cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"',width:180},
            {field: 'status',displayName: '菜单状态',width: 180,cellTemplate:
                    '<span ng-show="grid.appScope.hasPermit(\'appMenuAction.saveSwitch\')"><switch class="switch switch-s" ng-model="row.entity.status" ng-true-value="1" ng-false-value="0" ng-change="grid.appScope.updateStatus(row.entity)" /></span>'
                    +'<span ng-show="!grid.appScope.hasPermit(\'appMenuAction.saveSwitch\')"> <span ng-show="row.entity.status==1">开启</span><span ng-show="row.entity.status==0">关闭</span></span>'
            },
            { field: 'btnLink',displayName:'关联活动地址',width:400},
            { field: 'id',displayName:'操作',width:180,pinnedRight:true, cellTemplate:
                '<div class="lh30">'+
                    '<a target="_blank" ng-click="grid.appScope.modalShow(row.entity,true)">详情 </a> ' +
                    '<a target="_blank" ng-show="grid.appScope.hasPermit(\'appMenuAction.saveInfo\')" ng-click="grid.appScope.modalShow(row.entity,false)"> | 修改</a> ' +
                '</div>'
            }
        ],
        onRegisterApi: function(gridApi) {
            $scope.gridApi = gridApi;
            gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                $scope.paginationOptions.pageNo = newPage;
                $scope.paginationOptions.pageSize = pageSize;
                $scope.query();
            });
        }
    };
    $scope.query=function(){
        if ($scope.loadImg) {
            return;
        }
        $scope.loadImg = true;
        var data = {
            info:angular.toJson($scope.info),
            pageNo:$scope.paginationOptions.pageNo,
            pageSize:$scope.paginationOptions.pageSize
        };
        $http.post("appMenuAction/selectAll",data,$scope.postCfgAllCurrency)
            .success(function(data){
                if(data.status){
                    $scope.result=data.page.result;
                    $scope.userGrid.totalItems = data.page.totalCount;
                }else{
                    $scope.notice(data.msg);
                }
                $scope.loadImg = false;
            }).error(function(data){
                $scope.notice(data.msg);
                $scope.loadImg = false;
            });
    };
    $scope.query();


    //上传图片,定义控制器路径
    var uploaderImg = $scope.uploaderImg = new FileUploader({
        url: 'upload/fileUpload.do',
        queueLimit: 1,   //文件个数
        removeAfterUpload: false,  //上传后删除文件
        headers : {'X-CSRF-TOKEN' : $scope.csrfData}
    });
    //过滤长度，只能上传一个
    uploaderImg.filters.push({
        name: 'imageFilter',
        fn: function(item, options) {
            if(item.size>500*1024){
                return false;
            }
            return this.queue.length < 1;
        }
    });
    //过滤格式
    uploaderImg.filters.push({
        name: 'imageFilter',
        fn: function(item,options) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
    });
    uploaderImg.onSuccessItem = function(fileItem,response, status, headers) {// 上传成功后的回调函数，在里面执行提交
        if (response.url != null) { // 回调参数url
            $scope.subInfo(response.url);
        }
    };

    $scope.modalShow = function(entity,isDetail){
        $scope.isDetail=isDetail;
        uploaderImg.clearQueue();
        $scope.addInfo=angular.copy(entity);
        $scope.addInfo.startTime=$scope.addInfo.startTime==null?null:moment($scope.addInfo.startTime).format('YYYY-MM-DD HH:mm:ss');
        $scope.addInfo.endTime=$scope.addInfo.endTime==null?null:moment($scope.addInfo.endTime).format('YYYY-MM-DD HH:mm:ss');
        $('#appModal').modal('show');
    };
    $scope.modalcancel = function(){
        $('#appModal').modal('hide');
    };

    //新增banner
    $scope.saveInfo = function(){
        if($scope.submitting){
            return;
        }
        if($scope.addInfo.startTime==null||$scope.addInfo.startTime=="" ||$scope.addInfo.endTime==null||$scope.addInfo.endTime==""){
            $scope.notice("菜单开启时间不能为空!");
            return;
        }
        if($scope.addInfo.isWithParam==null||$scope.addInfo.isWithParam==="" ||$scope.addInfo.isWithParam==undefined){
            $scope.notice("跳转带参数不能为空!");
            return;
        }
        if(uploaderImg.queue.length<1){
            if($scope.addInfo.btnIcon==null||$scope.addInfo.btnIcon==="" ||$scope.addInfo.btnIcon==undefined){
                $scope.notice("菜单图标不能为空!");
                return;
            }
            $scope.subInfo(null);
        }else{
            uploaderImg.uploadAll();// 上传消息图片
        }
    };
    $scope.subInfo=function(val){
        $scope.submitting = true;
        //删除图片
        $scope.addInfo1=angular.copy($scope.addInfo);
        $scope.addInfo1.btnIcon=val;
        var data = {param:angular.toJson($scope.addInfo1)};
        $http.post("appMenuAction/saveInfo",data,$scope.postCfgAllCurrency)
            .success(function (result) {
                if (result.status) {
                    $scope.notice(result.msg);
                    $scope.query();
                    $scope.modalcancel();
                } else {
                    $scope.notice(result.msg);
                }
                $scope.submitting = false;
            }).error(function(data){
                $scope.submitting = false;
            });
    }

    //开启
    $scope.updateStatus = function(entity){
        var str="";
        var sta=0;
        if(entity.status){
            str="确认打开?";
            sta=1;
        }else{
            str="确认关闭?";
        }
        SweetAlert.swal({
                title: str,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "提交",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true },
            function (isConfirm) {
                if (isConfirm) {
                    $http.post("appMenuAction/saveSwitch","id="+entity.id+"&sta="+sta,
                        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
                        .success(function(data){
                            if(data.status){
                                $scope.notice(data.msg);
                                $scope.query();
                            }else{
                                entity.status = !entity.status;
                                $scope.notice(data.msg);
                            }
                        })
                        .error(function(data){
                            entity.status = !entity.status;
                        });

                }else{
                    entity.status = !entity.status;
                }
            });
    };

    //页面绑定回车事件
    $document.bind("keypress", function(event) {
        $scope.$apply(function (){
            if(event.keyCode == 13){
                $scope.query();
            }
        })
    });
});